<template>
  <q-page class="q-pa-md">
    <div class="row q-gutter-md">
      <!-- 左侧控制面板 -->
      <div class="col-12 col-md-4">
        <q-card>
          <q-card-section>
            <div class="text-h6 q-mb-md">
              <q-icon name="archive" class="q-mr-sm" />
              DICOM压缩包加载
            </div>
            
            <!-- 压缩包选择 -->
            <q-file
              v-model="selectedZipFile"
              label="选择压缩包文件"
              accept=".zip,.rar,.7z"
              max-file-size="500000000"
              @update:model-value="onZipFileSelected"
              class="q-mb-md"
            >
              <template v-slot:prepend>
                <q-icon name="archive" />
              </template>
            </q-file>

            <!-- 解压进度 -->
            <q-card v-if="extracting" flat bordered class="q-mb-md">
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">解压进度</div>
                <q-linear-progress 
                  :value="extractProgress" 
                  color="primary" 
                  class="q-mb-sm"
                />
                <div class="text-caption">
                  {{ Math.round(extractProgress * 100) }}% - {{ extractStatus }}
                </div>
              </q-card-section>
            </q-card>

            <!-- 压缩包信息 -->
            <q-card v-if="zipInfo" flat bordered class="q-mb-md">
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">压缩包信息</div>
                <q-list dense>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>文件名</q-item-label>
                      <q-item-label>{{ zipInfo.fileName }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>文件大小</q-item-label>
                      <q-item-label>{{ formatFileSize(zipInfo.fileSize) }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>总文件数</q-item-label>
                      <q-item-label>{{ zipInfo.totalFiles }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>DICOM文件数</q-item-label>
                      <q-item-label>{{ zipInfo.dicomFiles }}</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-card-section>
            </q-card>

            <!-- 文件列表 -->
            <q-card v-if="extractedFiles.length > 0" flat bordered class="q-mb-md">
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">
                  DICOM文件列表 ({{ extractedFiles.length }})
                </div>
                <q-scroll-area style="height: 200px;">
                  <q-list dense>
                    <q-item
                      v-for="(file, index) in extractedFiles"
                      :key="index"
                      clickable
                      @click="selectFile(index)"
                      :class="{ 'bg-primary text-white': currentFileIndex === index }"
                    >
                      <q-item-section avatar>
                        <q-icon name="description" />
                      </q-item-section>
                      <q-item-section>
                        <q-item-label>{{ file.name }}</q-item-label>
                        <q-item-label caption>{{ formatFileSize(file.size) }}</q-item-label>
                      </q-item-section>
                      <q-item-section side>
                        <q-badge v-if="currentFileIndex === index" color="white" text-color="primary">
                          当前
                        </q-badge>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-scroll-area>
              </q-card-section>
            </q-card>

            <!-- 批量操作 -->
            <q-card v-if="extractedFiles.length > 0" flat bordered>
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">批量操作</div>
                
                <q-btn-group spread class="q-mb-md">
                  <q-btn 
                    size="sm" 
                    color="positive" 
                    icon="play_arrow" 
                    label="播放"
                    @click="startSlideshow"
                    :disable="isPlaying"
                  />
                  <q-btn 
                    size="sm" 
                    color="negative" 
                    icon="stop" 
                    label="停止"
                    @click="stopSlideshow"
                    :disable="!isPlaying"
                  />
                </q-btn-group>

                <q-btn-group spread>
                  <q-btn 
                    size="sm" 
                    color="info" 
                    icon="download" 
                    label="导出"
                    @click="exportFiles"
                  />
                  <q-btn 
                    size="sm" 
                    color="warning" 
                    icon="delete" 
                    label="清空"
                    @click="clearFiles"
                  />
                </q-btn-group>
              </q-card-section>
            </q-card>
          </q-card-section>
        </q-card>
      </div>

      <!-- 右侧显示区域 -->
      <div class="col-12 col-md-8">
        <q-card style="height: 600px;">
          <q-card-section class="full-height">
            <div v-if="extractedFiles.length === 0" class="flex flex-center full-height">
              <div class="text-center">
                <q-icon name="archive" size="64px" color="grey-5" class="q-mb-md" />
                <div class="text-h6 text-grey-6">请选择压缩包文件</div>
                <div class="text-body2 text-grey-5">支持 ZIP、RAR、7Z 格式</div>
                <div class="text-caption text-grey-4 q-mt-sm">
                  自动解压并加载其中的DICOM文件
                </div>
              </div>
            </div>
            
            <div v-else class="full-height">
              <!-- DICOM图像显示容器 -->
              <div
                ref="dicomContainer"
                class="dicom-viewer full-height"
                style="background: #000; position: relative;"
              >
                <div v-if="loading" class="flex flex-center full-height">
                  <q-spinner-cube color="primary" size="40px" />
                </div>
                
                <!-- 图像信息叠加 -->
                <div v-if="currentFileIndex >= 0" class="image-overlay">
                  <div class="text-white text-caption">
                    {{ currentFileIndex + 1 }} / {{ extractedFiles.length }}
                  </div>
                  <div class="text-white text-caption">
                    {{ extractedFiles[currentFileIndex]?.name }}
                  </div>
                  <div class="text-white text-caption">
                    来源: {{ zipInfo?.fileName }}
                  </div>
                </div>

                <!-- 导航控制 -->
                <div class="navigation-controls">
                  <q-btn
                    round
                    color="primary"
                    icon="chevron_left"
                    @click="previousImage"
                    :disable="currentFileIndex <= 0"
                    class="nav-btn nav-btn-left"
                  />
                  <q-btn
                    round
                    color="primary"
                    icon="chevron_right"
                    @click="nextImage"
                    :disable="currentFileIndex >= extractedFiles.length - 1"
                    class="nav-btn nav-btn-right"
                  />
                </div>
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 响应式数据
const selectedZipFile = ref<File | null>(null)
const extracting = ref(false)
const extractProgress = ref(0)
const extractStatus = ref('')
const loading = ref(false)
const extractedFiles = ref<File[]>([])
const currentFileIndex = ref(-1)
const dicomContainer = ref<HTMLElement | null>(null)

// 压缩包信息
const zipInfo = ref<{
  fileName: string
  fileSize: number
  totalFiles: number
  dicomFiles: number
} | null>(null)

// 播放控制
const isPlaying = ref(false)
let slideshowInterval: number | null = null

// 压缩包文件选择处理
const onZipFileSelected = async (file: File | null) => {
  if (!file) return
  
  extracting.value = true
  extractProgress.value = 0
  extractStatus.value = '开始解压...'
  
  try {
    await extractZipFile(file)
  } catch (error) {
    console.error('解压文件失败:', error)
    $q.notify({
      type: 'negative',
      message: '解压文件失败',
      caption: '请检查文件格式是否正确'
    })
  } finally {
    extracting.value = false
  }
}

// 解压ZIP文件
const extractZipFile = async (file: File) => {
  // 这里应该使用JSZip库来解压文件
  // 目前先模拟解压过程
  
  extractStatus.value = '读取压缩包...'
  extractProgress.value = 0.1
  await new Promise(resolve => setTimeout(resolve, 500))
  
  extractStatus.value = '分析文件结构...'
  extractProgress.value = 0.3
  await new Promise(resolve => setTimeout(resolve, 500))
  
  extractStatus.value = '提取DICOM文件...'
  extractProgress.value = 0.6
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  extractStatus.value = '完成解压'
  extractProgress.value = 1.0
  
  // 模拟解压出的DICOM文件
  const mockFiles: File[] = []
  for (let i = 1; i <= 10; i++) {
    const fileName = `IMG-${String(i).padStart(4, '0')}.dcm`
    const mockFile = new File([new ArrayBuffer(1024 * 1024)], fileName, { type: 'application/dicom' })
    mockFiles.push(mockFile)
  }
  
  extractedFiles.value = mockFiles
  currentFileIndex.value = 0
  
  zipInfo.value = {
    fileName: file.name,
    fileSize: file.size,
    totalFiles: 15, // 假设压缩包中有15个文件
    dicomFiles: mockFiles.length
  }
  
  await loadCurrentImage()
  
  $q.notify({
    type: 'positive',
    message: '压缩包解压成功',
    caption: `提取了 ${mockFiles.length} 个DICOM文件`
  })
}

// 选择文件
const selectFile = async (index: number) => {
  if (index < 0 || index >= extractedFiles.value.length) return
  
  currentFileIndex.value = index
  await loadCurrentImage()
}

// 加载当前图像
const loadCurrentImage = async () => {
  if (currentFileIndex.value < 0 || currentFileIndex.value >= extractedFiles.value.length) return
  
  loading.value = true
  const currentFile = extractedFiles.value[currentFileIndex.value]
  
  try {
    // 这里应该使用Cornerstone.js加载和显示DICOM文件
    console.log('加载图像:', currentFile.name)
    
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 200))
  } finally {
    loading.value = false
  }
}

// 幻灯片播放
const startSlideshow = () => {
  if (extractedFiles.value.length <= 1) return
  
  isPlaying.value = true
  slideshowInterval = window.setInterval(() => {
    if (currentFileIndex.value >= extractedFiles.value.length - 1) {
      currentFileIndex.value = 0
    } else {
      currentFileIndex.value++
    }
    loadCurrentImage()
  }, 1000) // 每秒切换一张
}

const stopSlideshow = () => {
  isPlaying.value = false
  if (slideshowInterval) {
    clearInterval(slideshowInterval)
    slideshowInterval = null
  }
}

// 导航控制
const previousImage = () => {
  if (currentFileIndex.value > 0) {
    selectFile(currentFileIndex.value - 1)
  }
}

const nextImage = () => {
  if (currentFileIndex.value < extractedFiles.value.length - 1) {
    selectFile(currentFileIndex.value + 1)
  }
}

// 导出文件
const exportFiles = () => {
  $q.notify({
    type: 'info',
    message: '导出功能',
    caption: '此功能将在后续版本中实现'
  })
}

// 清空文件
const clearFiles = () => {
  $q.dialog({
    title: '确认清空',
    message: '确定要清空所有已解压的文件吗？',
    cancel: true,
    persistent: true
  }).onOk(() => {
    stopSlideshow()
    extractedFiles.value = []
    currentFileIndex.value = -1
    zipInfo.value = null
    selectedZipFile.value = null
    
    $q.notify({
      type: 'positive',
      message: '已清空所有文件'
    })
  })
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

onMounted(() => {
  console.log('初始化DICOM压缩包查看器')
})

onUnmounted(() => {
  stopSlideshow()
  console.log('清理DICOM压缩包查看器资源')
})
</script>

<style scoped>
.dicom-viewer {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.image-overlay {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.8);
  padding: 8px 12px;
  border-radius: 4px;
  z-index: 10;
}

.navigation-controls {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  pointer-events: none;
}

.nav-btn {
  pointer-events: auto;
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.nav-btn:hover {
  opacity: 1;
}

.nav-btn-left {
  position: absolute;
  left: 10px;
}

.nav-btn-right {
  position: absolute;
  right: 10px;
}

.full-height {
  height: 100%;
}
</style>

